package com.example.deepai.controller;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.Files;
import java.util.Base64; 

@RestController
@RequestMapping("/api")
public class FileController {
    
    // 添加配置项
    @Value("${screenshots.directory}")
    private String screenshotsDirectory;
    
    @GetMapping("/screenshots/{filename:.+}")
    public ResponseEntity<Resource> getScreenshot(@PathVariable String filename) {
        try {
            // 使用配置的目录路径
            Path screenshotsPath = Paths.get(screenshotsDirectory);
            if (!Files.exists(screenshotsPath)) {
                Files.createDirectories(screenshotsPath);
            }
            
            Path filePath = screenshotsPath.resolve(filename).normalize();
            
            // 安全检查：确保请求的文件在screenshots目录下
            if (!filePath.startsWith(screenshotsPath)) {
                return ResponseEntity.badRequest().build();
            }
            
            // 添加文件权限检查
            if (!Files.isReadable(filePath)) {
                System.out.println("File not readable: " + filePath.toAbsolutePath());
                return ResponseEntity.status(HttpStatus.FORBIDDEN).build();
            }
            
            // 添加更详细的日志
            System.out.println("File exists: " + Files.exists(filePath));
            System.out.println("File size: " + Files.size(filePath));
            System.out.println("File permissions: " + Files.getPosixFilePermissions(filePath));
            
            // 添加日志输出
            System.out.println("Accessing screenshot: " + filePath.toAbsolutePath());
            
            // 确保文件存在
            if (!Files.exists(filePath)) {
                System.out.println("File not found: " + filePath.toAbsolutePath());
                return ResponseEntity.notFound().build();
            }
            
            // 使用 ByteArrayResource 而不是 FileSystemResource
            byte[] imageBytes = Files.readAllBytes(filePath);
            ByteArrayResource resource = new ByteArrayResource(imageBytes);
            
            // 根据文件扩展名确定正确的 MediaType
            String contentType = determineContentType(filename);
            
            return ResponseEntity.ok()
                .contentType(MediaType.parseMediaType(contentType))  // 使用正确的 MediaType
                .header(HttpHeaders.CONTENT_DISPOSITION, "inline; filename=\"" + filename + "\"")
                .header("Access-Control-Allow-Origin", "*")
                .header("Cache-Control", "no-cache")
                .contentLength(imageBytes.length)
                .body(resource);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.internalServerError().build();
        }
    }
    
    // 添加这个辅助方法来确定文件的 MediaType
    private String determineContentType(String filename) {
        String extension = filename.substring(filename.lastIndexOf(".") + 1).toLowerCase();
        switch (extension) {
            case "png":
                return "image/png";
            case "jpg":
            case "jpeg":
                return "image/jpeg";
            case "gif":
                return "image/gif";
            case "bmp":
                return "image/bmp";
            default:
                return "application/octet-stream";
        }
    }
    
    @GetMapping("/screenshots/base64/{filename:.+}")
    public ResponseEntity<String> getScreenshotBase64(@PathVariable String filename) {
        try {
            Path filePath = Paths.get(screenshotsDirectory, filename);
            byte[] imageBytes = Files.readAllBytes(filePath);
            String base64Image = Base64.getEncoder().encodeToString(imageBytes);
            return ResponseEntity.ok()
                .contentType(MediaType.TEXT_PLAIN)
                .body(base64Image);
        } catch (Exception e) {
            return ResponseEntity.notFound().build();
        }
    }
}